package com.yuyang.wifi.dialog;


import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import androidx.annotation.Nullable;

/**
 * Created by wislie on 2017/8/14.
 */

public abstract class BaseDialogFragment extends DialogFragment {

    //根目录
    private View mRootView;

//    private boolean mIsDismiss;

    //    private Animation mFadeOutAnim;
    protected DialogListener mDialogListener;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        if (!hasTitle()) {
            getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        }
        if (getLayoutId() == 0) throw new RuntimeException("需要设置布局文件");
        View rootView = inflater.inflate(getLayoutId(), container, false);
        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        viewCreated(view, savedInstanceState);
        if (view != null) {
            mRootView = view;
//            if (animOut() != 0) {
//                mRootView.startAnimation(AnimationUtils.loadAnimation(getActivity(), animOut()));
//            }

//            if (animIn() != 0) {
//                mRootView.startAnimation(AnimationUtils.loadAnimation(getActivity(), animIn()));
//            }

            // if (animOut() == 0) return;
          /*  mFadeOutAnim = AnimationUtils.loadAnimation(getActivity(), animOut());

            mFadeOutAnim.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    BaseDialogFragment.super.dismiss();
                    dismissDialog();
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }
            });*/
        }

    }

    @Override
    public void onStart() {
        super.onStart();

        Window window = getDialog().getWindow();
        WindowManager.LayoutParams params = window.getAttributes();

        params.gravity = getGravity();
        params.width = getWidth();
        params.height = getHeight();

        if (dimAmountIsZero()) {
            params.dimAmount = 0;
        }

        if (getX() != 0) {
            params.x = getX();
        }

        if (getY() != 0) {
            params.y = getY();
        }
        //window.setWindowAnimations(R.style.DialogAnim);
        setCancelable(isCancelable());
        window.setAttributes(params);
        window.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00000000")));
        //确实可以起到动画的作用，只是动画设置的不好看
//        window.setWindowAnimations(R.style.dialog_anim);

       /* window.getDecorView().setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if((isCancelable())){
                    dismiss();
                }
                return true;
            }
        });*/
    }


    @Override
    public void dismiss() {
        Log.e("wislie", "dismiss");


        // DialogFragment.show() will take care of adding the fragment
        // in a transaction.  We also want to remove any currently showing
        // dialog, so make our own transaction and take care of that here.


//        if (mRootView != null) {
//            if (animOut() == 0) {
//                BaseDialogFragment.super.dismiss();
//                dismissDialog();
//                return;
//            }
//
//        }
        if (mRootView != null) {
            if (animIn() == 0) {
                BaseDialogFragment.super.dismiss();
                dismissDialog();
                return;
            } else {
                mRootView.startAnimation(AnimationUtils.loadAnimation(getActivity(), animIn()));
            }
        }

        super.dismiss();
    }

    //主动关闭dialog
    public void dismiss(FragmentManager fragmentManager) {
        try {
            if (this == null) return;
            if (null != fragmentManager) {
                FragmentTransaction ft = fragmentManager.beginTransaction();
                Fragment prev = fragmentManager.findFragmentByTag(getTag());
                if (prev != null) {
                    ft.remove(prev);
                }
                fragmentManager.popBackStack();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 是否有标题
     */
    public abstract boolean hasTitle();

    /**
     * 得到资源布局id
     *
     * @return
     */
    public abstract int getLayoutId();

    /**
     * 是否点击是否会消失
     *
     * @return
     */
    public abstract boolean isCancelable();

    /**
     * 创建好的视图
     *
     * @param view
     * @param savedInstanceState
     */
    public abstract void viewCreated(View view, @Nullable Bundle savedInstanceState);


    /**
     * 设置对话框位置
     *
     * @return
     */
    public abstract int getGravity();

    /**
     * 设置对话框宽度
     *
     * @return
     */
    public abstract int getWidth();

    /**
     * 设置对话框高度
     *
     * @return
     */
    public abstract int getHeight();

    /**
     * 设置对话框弹出后当前的 activity背景不变暗
     *
     * @return 返回值为true表示不变暗, 否则变暗
     */
    public abstract boolean dimAmountIsZero();

    /**
     * 设置对话框左上角的x坐标
     *
     * @return
     */
    public abstract int getX();

    /**
     * 设置对话框左上角的y坐标
     *
     * @return
     */
    public abstract int getY();

    /**
     * 视图打开时的动画
     *
     * @return
     */
    public abstract int animIn();

    /**
     * 视图退出时的动画
     *
     * @return
     */
    public abstract int animOut();

    /**
     * 视图退出
     */
    public abstract void dismissDialog();

    /**
     * 弹出对话框
     *
     * @param fragmentManager
     */
    public void showDialog(FragmentManager fragmentManager) {
        if (this == null) return;

        // DialogFragment.show() will take care of adding the fragment
        // in a transaction.  We also want to remove any currently showing
        // dialog, so make our own transaction and take care of that here.
        FragmentTransaction ft = fragmentManager.beginTransaction();
        Fragment prev = fragmentManager.findFragmentByTag(getTag());
        if (prev != null) {
            ft.remove(prev);
        }
        ft.addToBackStack(null);
        // Create and show the dialog.
        show(ft, getTag());
    }

    public void setOnDialogListener(DialogListener listener) {
        mDialogListener = listener;
    }


    public interface DialogListener {
        //对话框确认
        void onConfirm();

        /**
         * 输入确定
         *
         * @param
         */
        void onInputConfirm(String... values);

        //取消
        void onCancel();

        //发送验证码
        void onSendCode();

//        void weChat();
//
//        void friends();
//
//        void links();

    }

    //**********************************避免dialog调用onSaveInstanceState发生崩溃**************************************//
    private Method noteStateNotSavedMethod;
    private Object fragmentMgr;
    private String[] activityClassName = {"Activity", "FragmentActivity"};


    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        invokeFragmentManagerNoteStateNotSaved();
    }

    private void invokeFragmentManagerNoteStateNotSaved() {
        //java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
            return;
        }
        try {
            if (noteStateNotSavedMethod != null && fragmentMgr != null) {
                noteStateNotSavedMethod.invoke(fragmentMgr);
                return;
            }
            Class cls = getClass();
            do {
                cls = cls.getSuperclass();
            } while (!(activityClassName[0].equals(cls.getSimpleName())
                    || activityClassName[1].equals(cls.getSimpleName())));

            Field fragmentMgrField = prepareField(cls, "mFragments");
            if (fragmentMgrField != null) {
                fragmentMgr = fragmentMgrField.get(this);
                noteStateNotSavedMethod = getDeclaredMethod(fragmentMgr, "noteStateNotSaved");
                if (noteStateNotSavedMethod != null) {
                    noteStateNotSavedMethod.invoke(fragmentMgr);
                }
            }

        } catch (Exception ex) {
        }
    }

    private Field prepareField(Class<?> c, String fieldName) throws NoSuchFieldException {
        while (c != null) {
            try {
                Field f = c.getDeclaredField(fieldName);
                f.setAccessible(true);
                return f;
            } finally {
                c = c.getSuperclass();
            }
        }
        throw new NoSuchFieldException();
    }

    private Method getDeclaredMethod(Object object, String methodName, Class<?>... parameterTypes) {
        Method method = null;
        for (Class<?> clazz = object.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) {
            try {
                method = clazz.getDeclaredMethod(methodName, parameterTypes);
                return method;
            } catch (Exception e) {
            }
        }
        return null;
    }

}
